package com.example.todolist.config.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.example.todolist.entity.User;
import com.example.todolist.mapper.UserMapper;
import com.example.todolist.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        String token = request.getHeader("token");// 从 http 请求头中取出 tokenyg
        Integer userIdRequest = Integer.parseInt(request.getParameter("userId"));
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (token == null) {
            throw new RuntimeException("无token，请重新登录");
        }
        Integer userIdToken;
        try {
            userIdToken = Integer.parseInt(JWT.decode(token).getAudience().get(0));
        } catch (JWTDecodeException j) {
            throw new RuntimeException("token验证失败");
        }
        User user = userMapper.findByUserId(userIdToken);
        if (user == null) {
            throw new RuntimeException("非法访问");
        }
        if (!userIdRequest.equals(userIdToken))
        {
            throw new RuntimeException("非法访问");
        }
        //验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TokenUtils.secret)).build();
        try {
            jwtVerifier.verify(token);   //验证token
        } catch (JWTVerificationException e) {
            throw new RuntimeException("token验证失败");
        }
        return true;
    }
}
